using DotNetty.Buffers;
using DotNetty.Transport.Channels;
using System;
using System.Net.Sockets;
using System.Net;
using Assets.Client.RunTime.Manager;

public class UdpClientHandler : ChannelHandlerAdapter
{
    public UdpClientHandler()
    {

    }

    public override void ChannelActive(IChannelHandlerContext context)
    {

    }

    public override void ChannelRead(IChannelHandlerContext context, object message)
    {
        Messages.IMessage iMessage = message as Messages.IMessage;
        if (iMessage.Sender == null)
        {
            return;
        }
        if (iMessage.Sender.Host == GetLocalHostIp() && iMessage.Sender.Port == Client.UdpPort)
        {
            return;
        }
        MessagePublisher.Single.NotifyMessage(iMessage);
    }

    public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
    {
        UnityEngine.Debug.LogFormat("Exception: {0}", exception);
        context.CloseAsync();
    }

    private static string localHost = string.Empty;

    /// <summary>
    /// 获取本机ipv4
    /// </summary>
    /// <returns></returns>
    public static string GetLocalHostIp()
    {
        if (!string.IsNullOrEmpty(localHost))
        {
            return localHost;
        }
        IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                localHost = ip.ToString();
                return localHost;
            }
        }
        return string.Empty;
    }
}
